<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Call extends Controller_Tpl {
    //private $_data;

	public function before()
	{
		parent::before();
	}

	public function after()
	{
		parent::after();
	}

	public function action_index()
	{
		$query = DB::select()
			->from('leads')
			->join('clients','LEFT')
			->on('leads.leadsid', '=', 'clients.lead_id')
			->where('clients.status_id','IS',NULL);
		$pagination_query = clone $query;
		$count = $pagination_query->select(DB::expr('COUNT(*) AS count'))->execute()->get('count');

		$config = Kohana::$config->load('pagination');
		$pagination = Pagination::factory(array(
			'total_items' => $count,
			'current_page'   => array('source' => 'route', 'key' => 'page'),
			'items_per_page' => 20,
			'view'           => 'pagination/floating',
			'auto_hide'      => TRUE,
		));
		$this->_data['page_links'] = $pagination->render();

		$query->order_by('date', 'DESC')
			->limit($pagination->items_per_page)
			->offset($pagination->offset);
		$this->_data['leads'] = $query->execute()->as_array();
		$this->_data['table_new'] = View::factory($this->_data['controller'].'/blocks/leadstable',$this->_data);

		$query = DB::select()
			->from('leads')
			->join('clients','LEFT')
			->on('leads.leadsid', '=', 'clients.lead_id')
			->where('clients.status_id','IS NOT',NULL);
		$pagination_query = clone $query;
		$count = $pagination_query->select(DB::expr('COUNT(*) AS count'))->execute()->get('count');

		$config = Kohana::$config->load('pagination');
		$pagination = Pagination::factory(array(
			'total_items' => $count,
			'current_page'   => array('source' => 'route', 'key' => 'page'),
			'items_per_page' => 20,
			'view'           => 'pagination/floating',
			'auto_hide'      => TRUE,
		));
		$this->_data['page_links'] = $pagination->render();

		$query->order_by('date', 'DESC')
			->limit($pagination->items_per_page)
			->offset($pagination->offset);
		$this->_data['leads'] = $query->execute()->as_array();
		$this->_data['table_my'] = View::factory($this->_data['controller'].'/blocks/leadstable',$this->_data);
		//echo Database::instance()->last_query;
	}

	public function action_form()
	{
		if ($this->request->method() === HTTP_Request::POST)
		{			$lead = DB::select()
				->from('leads')
				->join('clients','LEFT')
				->on('leads.leadsid', '=', 'clients.lead_id')
				->where('leads.leadsid','=',$this->_data['id'])
				->limit(1)
				->execute()
				->current();
			switch ($this->request->post('action')) {
				case 'cal':
					if (empty($lead['clientsid']))
					{						DB::insert('clients', array('lead_id', 'status_id', 'visit'))
							->values(array($lead['leadsid'], 1, $this->request->post('visit')))
							->execute();					}
					else
					{						DB::update('clients')
							->set(array('status_id'=>1,'visit'=>$this->request->post('visit')))
							->where('lead_id','=',$lead['leadsid'])
							->execute();					}
				break;
				case 'card':
					if (empty($lead['clientsid']))
					{
						DB::insert('clients', array('lead_id', 'status_id', 'visit'))
							->values(array($lead['leadsid'], 1, $this->request->post('visit')))
							->execute();
					}
					else
					{
						DB::update('leads')
							->set(array('phone'=>$this->request->post('phone'),'name'=>$this->request->post('name'),'leadstext'=>$this->request->post('leadstext')))
							->where('leadsid','=',$lead['leadsid'])
							->execute();
					}
				break;
				case '123':
				echo '123';
				break;
			}
			//echo 'POST';		}
		else
		{
			if (isset($this->_data['id']))
			{
				$this->_data['lead'] = DB::select()->from('leads')
					->join('clients','LEFT')
					->on('leads.leadsid', '=', 'clients.lead_id')
					->where('leads.leadsid','=',$this->_data['id'])
					->limit(1)
					->execute()
					->current();
					if (empty($this->_data['lead']['clientsid']))
					{
						DB::insert('clients', array('lead_id'))
							->values(array($this->_data['lead']['leadsid']))
							->execute();
					}
				$calendar = DB::select('visit',array(DB::expr('COUNT(`visit`)'),'count'))->from('clients')
					->where('status_id','=',1)
					->and_where('visit', 'BETWEEN', array(strtotime("Monday this week"),strtotime("Sunday")))
					->group_by('visit')
					->execute()
					->as_array();
				//echo Database::instance()->last_query;
				//print_r($this->_data['calendar']);
				foreach($calendar as &$row)
				{					$this->_data['calendar'][$row['visit']] = $row['count'];				}

			}
			$additional = Model::factory('Admin')->get_data('additional');
			$chunk = ceil(count($additional)/3);
			$this->_data['additional'] = $chunk>0?array_chunk($additional,$chunk):array();
			$subjects = Model::factory('Admin')->get_data('subjects');
			$chunk = ceil(count($subjects)/4);
			$this->_data['subjects'] = $chunk>0?array_chunk($subjects,$chunk):array();
			//print_r($this->_data['additional']);
			//exit();

			$this->_data['worktime']['start'] = 9;
			$this->_data['worktime']['end'] = 20;
			//$this->_data['calendar'] = array();
			$this->_data['im'] = !empty($this->_data['lead']['visit'])?$this->_data['lead']['visit']:0;
		}
	}

	public function action_imap()
	{
		set_time_limit(0);
		Imap::instance()->connect("imap.gmail.com", "leadsfor", "rabota9610", '[Gmail]/&BBIEQQRP- &BD8EPgRHBEIEMA-', 993, /*'ssl/novalidate-cert'*/'imap/ssl');
		if (Imap::instance()->isConnected())
		{
            //$mailbox = Imap::instance()->getMailboxes();
            //print_r($mailbox);
            //exit();
			$messages = Imap::instance()->getMessages();
			//print_r($messages);
			//exit();
			foreach($messages as &$message)
			{
				if (empty($message['msgno']))
				{
					//echo $message['msgno'];
					continue;
				}
				$msg = Imap::instance()->getMessage($message['msgno']);
				$msg['date'] = $message['date'];
				$msg['msgno'] = $message['msgno'];
				$msg['sender'] = $message['sender'];
				$msg['status'] = $message['status'];

				if (isset($msg['plain']))
				{
					$body = $msg['plain'];
				}
				elseif (isset($msg['html']))
				{
					$body = $msg['html'];
				}
				// anaferka@gmail.com /����� ������ � �������/
				if (preg_match('~<p>(.*?){1,64}<br>(.*?){6,20}<br>(.*?)</p>~si',$body,$m))
				{
					//print_r($m);
					//exit();
					DB::insert('leads')
						->columns(array('date', 'phone', 'from', 'name', 'text'))
						->values(array($msg['date'], $m[2], 1, $m[1], $m[3]))
						->execute();
					echo '.';
				}
				unset($msg);
			}
		}

/*
		if (isset($message['plain']))
		{
			$message = $message['plain'];
		}
		elseif (isset($message['html']))
		{
			$message = $message['html'];
		}
		// ����� ������ � �������


*/
	}
} // End Call